package timeline.util;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;


public class TimeLineClient {
	private final static Logger logger = Logger.getLogger(TimeLineClient.class
			.getName());
	
	public  Object send(String targetName, int port, Object object) {
		Socket socket = null;
		ObjectOutputStream os = null;
		ObjectInputStream is = null;

		try {
			socket = new Socket(targetName, port);
			os = new ObjectOutputStream(socket.getOutputStream());
			os.writeObject(object);
			os.flush();

			is = new ObjectInputStream(new BufferedInputStream(
					socket.getInputStream()));
			Object obj = is.readObject();
			return obj;
		} catch (IOException ex) {
			logger.log(Level.SEVERE, null, ex);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (Exception ex) {
			}
			try {
				os.close();
			} catch (Exception ex) {
			}
			try {
				socket.close();
			} catch (Exception ex) {
			}
		}
		return null;
	}
	
	public interface ClientCallBack{
		public void OnCallBack(ConcurrentHashMap<String,Object> object);
	}
	
	public void send(String targetName,int port,final Object objlib , final ClientCallBack clientCallBack) {
		new Thread(){
			public  void run() {
				System.out.println("send: "+objlib+" to "+targetName+":"+port+" for execute!");
				Object object =  send(targetName,port, objlib);
				ConcurrentHashMap<String,Object> map = (ConcurrentHashMap<String, Object>) object;
				if(clientCallBack!=null){
					clientCallBack.OnCallBack(map);
				}
			};
		}.start();
		
	}
}
